<?php

class Reservations_AddAction extends SrsReservationsBaseAction
{
	public function getCredentials()
	{
		return 'reservations.add';
	}

	public function executeRead(AgaviRequestDataHolder $rd)
	{
		$hall = $this->getTable('Hall')->find($rd->getParameter('hall'));

		if (!$hall instanceof Hall) return $this->forward404();
		
		$this->setAttribute('hall', $hall);

  	return 'Input';
	}

	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		$hall = (int)$rd->getParameter('hall');
		$r    = $rd->getParameter('reservation');

		$from = strtotime($r['date'] . ' ' . $r['from'] . ':00');
		$to   = strtotime($r['date'] . ' ' . $r['to'] . ':00');

		$overlappingReservations = array();

		foreach (Reservation::findOverlapping($hall, $from, $to) as $reservation)
		{
			if ($reservation->status === 'accepted' || $reservation->status === 'closed')
			{
				$this->addError('overlapping', 'reservation[period]', sprintf(
					'Podany termin jest już zajęty (od %s do %s).', date('H:i', $reservation->fromTime), date('H:i', $reservation->toTime)
				));

      	return 'Error';
			}
			else
			{
				$overlappingReservations[] = $reservation;
			}
		}

		$conn = $this->context->getDatabaseConnection();
		/* @var $conn Doctrine_Connection */

		$conn->beginTransaction();

		try
		{
			if (!empty($overlappingReservations))
			{
				foreach ($overlappingReservations as $reservation) $reservation->reject();
			}

			$reservation = new Reservation();
			$reservation->fromArray(array(
				'hallId'      => $hall,
				'creatorId'   => $this->context->getUser()->getCurrentUser()->id,
				'fromTime'    => $from,
				'toTime'      => $to,
				'department'  => $r['department'],
				'branch'      => $r['branch'],
				'year'        => $r['year'],
				'description' => $r['description'],
				'subject'     => $r['subject'],
				'lecturer'    => $r['lecturer'],
				'status'      => 'accepted',
			));
			$reservation->save();

			$conn->commit();
   	}
		catch (Doctrine_Exception $x)
		{
			$conn->rollback();

			$this->addError('exception', 'exception', $x->getMessage());

			return 'Error';
   	}

  	return 'Success';
	}
}